<template>
	<div class="app-container">
		<el-form class="" :model="form" :rules="rules" ref="queryRef" :inline="true" label-width="80px">
			<div class="bgWhite radius8 pt30">
				<div class="text-center fb fs16 border-bottom pb30">
					基础信息
				</div>
				<div class="p20">
					<el-form-item label="客户姓名" prop="customerName" label-width="80px">
						<el-input size="large" v-model="form.customerName" style="width: 200px"
							placeholder="请填写" />
					</el-form-item>
					<el-form-item label="手机号码" prop="phoneNumber" label-width="80px">
						<el-input size="large" v-model="form.phoneNumber" style="width: 200px"
							placeholder="请填写" />
					</el-form-item>
					<el-form-item label="生日" prop="birthday" label-width="80px">
						<el-date-picker style="width: 200px;" v-model="form.birthday" type="date"
							placeholder="选择日期" size="large" @change="change1" />
					</el-form-item>
					<el-form-item label="客户尊称" prop="customerTitle" label-width="80px">
						<el-select v-model="form.customerTitle" placeholder="请选择" size="large"
							style="width: 200px">
							<el-option v-for="dict in honorific" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="所在地区" prop="localProvince" label-width="80px">
						<el-cascader v-model="addressNode" ref="cascader" style="width:200px;" :props="address"
							@change="handleChangeAddress" size="large" clearable>
						</el-cascader>
					</el-form-item>
					<el-form-item label="详细地址" prop="detailedAddress" label-width="80px">
						<el-input size="large" v-model="form.detailedAddress" style="width: 433px"
							placeholder="请填写" />
					</el-form-item>
					<el-form-item label="业务经理" prop="businessManagerId" label-width="80px">
						<el-select v-model="form.businessManagerId" placeholder="请选择" size="large"
							style="width: 200px">
							<el-option v-for="dict in teamOptions" :key="dict.userId" :label="dict.userName"
								:value="dict.userId" />
						</el-select>
					</el-form-item>
				</div>
			</div>
			<div class="bgWhite radius8 pt30 mt20">
				<div class="text-center fb fs16 border-bottom pb30">
					其他信息
				</div>
				<div class="p20">
					<!-- <el-form class="p20" :model="form" :rules="rules"  ref="queryRef" :inline="true"> -->
					<el-form-item label="客户类型" prop="customerType" label-width="100px">
						<el-radio-group v-model="form.customerType" style="width: 340px">
							<el-radio v-for="dict in bus_customer_type" :key="dict.value" :label="dict.value"
								:value="dict.value" size="large">
								{{dict.label}}
							</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="客户来源" prop="opportunityChannel" label-width="100px">
						<el-radio-group v-model="form.opportunityChannel" style="width: 340px">
							<el-radio v-for="dict in bus_channel" :key="dict.value" :label="dict.value"
								:value="dict.value" size="large">
								{{dict.label}}
							</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="来源渠道" prop="opportunitySource" label-width="100px">
						<el-select v-model="form.opportunitySource" placeholder="来源渠道" size="large"
							style="width: 340px">
							<el-option v-for="dict in bus_source" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="客户状态" prop="customerStatus" label-width="100px">
						<el-select v-model="form.customerStatus" placeholder="客户状态" size="large"
							style="width: 340px">
							<el-option v-for="dict in bus_customer_status" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="客户星级" prop="customerStarLevel" label-width="100px">
						<el-select v-model="form.customerStarLevel" placeholder="客户星级" size="large"
							style="width: 340px">
							<el-option v-for="dict in bus_customer_starlevel" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="客户标签" prop="customerLabels" label-width="100px">
						<el-select v-model="form.customerLabels" placeholder="客户标签" size="large"
							style="width: 340px">
							<el-option v-for="dict in bus_client_tag" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="痛点需求" prop="customerNeed" label-width="100px">
						<el-input v-model="form.customerNeed" style="width: 340px" :rows="3" type="textarea"
							placeholder="请输入痛点需求" resize="none" />
					</el-form-item>
					<el-row v-if="form.customerType != 1003">
						<el-col :span="24">
							<el-form-item label="统一社会信用代码" prop="creditCode" label-width="156px" style="width: 570px;">
								<el-input size="large" v-model="form.creditCode" style="width: 340px"
									placeholder="请填写" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row v-if="form.customerType != 1003">
						<el-col :span="24">
							<el-form-item label="门店图片" prop="storeImageUrl" label-width="100px" style="width: 570px;">
								<el-upload class="avatar-uploader" :action="url" :headers="headers"
									:show-file-list="false" :on-success="handleAvatarSuccess"
									:before-upload="beforeAvatarUpload">
									<img v-if="form.storeImageUrl" :src="form.storeImageUrl"
										class="shopImg" />
									<div v-else>
										<el-icon class="avatar-uploader-icon">
											<Plus />
										</el-icon>
										<div class="fs12">上传图片</div>
									</div>
								</el-upload>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<!-- </el-form> -->
			</div>
			<div class="bgWhite radius8 pt25 mt20">
				<div class="flex col-center row-between border-bottom pb25 pl20 pr20">
					<span class="fb fs16">{{form.customerType == '1003' ? '作物结构' :'销售情况'}}</span>
					<el-button type="defaultBtn" @click="handleAdd">添加信息</el-button>
				</div>
				<el-table :data="form.cropStructuresList" v-loading="loading" style="width: 100%;"
					:header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}"
					:cell-style="{height:'54px'}">
					<el-table-column label="年份" align="center" width="250px">
						<template #default="scope">
							<el-input v-model="scope.row.cropYear" style="width: 120px" size="large"
								placeholder="请输入年份" />
						</template>
					</el-table-column>
					<el-table-column label="主要产品" align="center" v-if="form.customerType != '1003'">
						<template #default="scope">
							<el-select v-model="scope.row.mainProducts" placeholder="选择主营产品" size="large"
								style="width: 160px">
								<el-option v-for="dict in productList" :key="dict.id" :label="dict.productName"
									:value="dict.id" />
							</el-select>
						</template>
					</el-table-column>
					<el-table-column label="销售规模(万元)" align="center" 
						v-if="form.customerType != '1003'">
						<template #default="scope">
							<el-input v-model="scope.row.salesVolume" style="width: 160px" size="large"
								placeholder="请输入年销售规模" />
						</template>
					</el-table-column>
					<el-table-column label="作物品种" align="center" width="250" v-if="form.customerType == '1003'">
						<template #default="scope">
							<el-select v-model="scope.row.cropVariety" placeholder="选择作物品种" size="large"
								style="width: 160px">
								<el-option v-for="dict in cropNameArr" :key="dict.id" :label="dict.cropName"
									:value="dict.id" />
							</el-select>
						</template>
					</el-table-column>
					<el-table-column label="种植面积（亩）" align="center" width="250"
						v-if="form.customerType == '1003'">
						<template #default="scope">
							<el-input v-model="scope.row.cropArea" style="width: 160px" size="large"
								placeholder="请输入种植面积" />
						</template>
					</el-table-column>
					<el-table-column label="农资年投入成本（元）" align="center" width="250"
						v-if="form.customerType == '1003'">
						<template #default="scope">
							<el-input v-model="scope.row.cropCost" style="width: 160px" size="large"
								placeholder="请输入农资年投入" />
						</template>
					</el-table-column>
					<el-table-column label="种植月份" align="center" width="250px" v-if="form.customerType == '1003'">
						<template #default="scope">
							<el-date-picker v-model="scope.row.cropMonth" type="month" placeholder="选择月份" format="MM"
								value-format="MM" size="large">
							</el-date-picker>
						</template>
					</el-table-column>
					<el-table-column fixed="right" label="操作" align="center"
						class-name="small-padding fixed-width">
						<template #default="scope">
							<span class="color-red cursor"
								@click="del(scope.$index, form.cropStructuresList)">删除</span>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<!-- 编辑的时候不显示 -->
			<div class="bgWhite radius8 pt25 mt20" v-if="customerId != ''">
				<div class="fb fs16 border-bottom pb25 pl20">
					创建下次跟进任务
				</div>
				<div class="p20">
					<!-- <el-form class="p20" :model="form" :rules="rules" ref="queryRef" :inline="true"> -->
					<el-form-item label="跟进时间" prop="followupTime" label-width="100px">
						<el-date-picker style="width: 270px" v-model="form.followupTime" type="datetime"
							placeholder="选择跟进时间" size="large" @change="change2" />
					</el-form-item>
					<el-form-item label="跟进内容" prop="followupContent" label-width="100px">
						<el-input size="large" v-model="form.followupContent" style="width: 270px"
							placeholder="请填写" />
					</el-form-item>
					<el-form-item label="跟进人员" prop="staffId" label-width="100px">
						<el-select v-model="form.staffId" placeholder="请选择" size="large" style="width: 270px">
							<el-option v-for="dict in teamOptions" :key="dict.userId" :label="dict.userName"
								:value="dict.userId" />
						</el-select>
					</el-form-item>
					<el-form-item label="任务提醒" prop="reminderType" label-width="100px">
						<el-select v-model="form.followupRecords.reminderType" placeholder="请选择" size="large"
							style="width: 270px">
							<el-option v-for="dict in bus_followup_task" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
					</el-form-item>
					<el-form-item label="提醒方式" prop="reminderMethod" label-width="100px">
						<el-radio-group v-model="form.followupRecords.reminderMethod" style="width: 270px">
							<el-radio v-for="dict in bus_reminder_method" :key="dict.value" :label="dict.label"
								:value="dict.value" size="large">
								{{dict.label}}
							</el-radio>
						</el-radio-group>
					</el-form-item>
				</div>
			</div>
		</el-form>
		<div class="text-center mt25">
			<el-button type="defaultBtn" @click="creatUser('queryRef')" style="height: 38px;">
				{{customerId == '' ? '创建' :'编辑'}}客户
			</el-button>
			<el-button type="operate" style="width: 88px;height: 38px;" v-if="customerId == ''"
				@click="resetQuery()">重置</el-button>
			<el-button style="width: 88px;height: 38px;" @click="closePage()">关闭</el-button>
		</div>
	</div>
</template>
<script setup name="addCustomer">
	const {
		proxy
	} = getCurrentInstance();
	const {
		bus_customer_status,
		bus_channel,
		bus_customer_type,
		bus_source,
		bus_customer_starlevel,
		bus_client_tag,
		honorific,
		bus_reminder_method,
		bus_followup_task
	} =
	proxy.useDict("bus_customer_status", "bus_channel", "bus_customer_type", "bus_source", "bus_customer_starlevel",
		"bus_client_tag", "honorific",
		"bus_reminder_method", "bus_followup_task");
</script>
<script>
	import {
		customerAdd,
		cropVariety,
		editCustomer,
		getCustomerDetail,
		productListAll
	} from "@/api/business/customer";
	import {
		getDivisions
	} from "@/api/business/opportunity";
	import {
		getOpportunityInfo,
		listOpportunity,
		teamAllocation,
		teamReceive,
		getUserListData
	} from "@/api/business/teamOpportunity";
	import {
		resetForm,
		getUserInfo
	} from '@/utils/ruoyi'
	import {
		getToken
	} from "@/utils/auth";
	let url = import.meta.env.VITE_APP_BASE_API + "/common/upload"
	let id = 0;
	export default {
		data() {
			return {
				headers: {
					Authorization: 'Bearer ' + getToken() // 这里的getToken方法需要你自己实现，用于获取你的Token
				},
				url: url,
				addressNode: [],
				address: {
					lazy: true,
					lazyLoad(node, resolve) {
						setTimeout(() => {
							const nodes = [];
							// 构造查询条件
							let query = {
								id: node.level == 0 ? 0 : node.value,
								level: node.level + 1,
								type: 'provinces',
								pCode: node.value,
								pageNum: 1,
								pageSize: 5000
							}
							if (query.level == 2) {
								query.type = 'cities';
								// form.customerAddress = node.label;
							}
							if (query.level == 3) {
								query.type = 'areas';
							}
							if (query.level == 4) {
								query.type = 'streets';
							}
							//查询接口
							getDivisions(query, query.type).then(res => {
								res.rows.map((item) => {
									let obj = {
										value: item.code,
										label: item.name,
										pCode: item.pCode,
										leaf: query.level >= 3
										//leaf: item.hasChildren // 节点级别，如果没有子节点就停止查询
									}
									nodes.push(obj);
								})
								//重新加载节点

								resolve(nodes);
							})
						}, 100);
					}
				},
				opportunityId: '', //商机id
				form: {
					customerName: '', //客户姓名
					customerType: '1003', //客户类型，默认农户
					customerTitle: '', //尊称
					opportunityChannel: '1001', //客户来源，默认线上
					phoneNumber: '', //手机号码
					opportunitySource: '', //来源渠道
					birthday: '', //生日
					customerStatus: '', //客户状态
					localProvince: '', //省
					localCity: '', //市
					localCounty: '', //县
					localArea: null, //区
					customerStarLevel: '', //客户星级
					detailedAddress: '', //详细地址,
					customerLabels: '', //客户标签
					businessManagerId: '', //业务经理
					creditCode: '', //统一社会信用代码
					storeImageUrl: '', //门店图片
					customerNeed: '', //痛点需求
					cropStructuresList: [{
						cropType: '', //类型1=作物结构2=销售情况
						cropYear: '', //年份
						cropVariety: '', //作物品种农户来源作物表的id
						cropArea: '', //种植面积（亩）
						cropCost: '', //农资年投入成本(元)
						cropMonth: '', //种植月份
						mainProducts: '', //主营产品经销商或零售有。来源作物id
						salesVolume: '' //销售规模(万元)
					}], //作物结构或销售情况
					followupTime: '',
					staffId: '',
					followupContent: '',
					followupRecords: {
						followupTime: '', //跟进时间
						followupContent: '', //跟进内容
						staffId: '', //跟进人员
						reminderMethod: '', //提醒方式
						reminderType: '', //任务提醒
					}, //跟进任务
				},
				rules: {
					customerName: [{
						required: true,
						message: '请输入客户姓名',
						trigger: 'blur'
					}, ],
					phoneNumber: [{
							required: true,
							message: '请输入手机号码',
							trigger: 'blur'
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: '手机号码格式不正确',
							trigger: 'blur'
						}
					],
					businessManagerId: [{
						required: true,
						message: '请选择业务经理',
						trigger: 'change'
					}, ],
					customerType: [{
						required: true,
						message: '请选择客户类型',
						trigger: 'change'
					}, ],
					opportunityChannel: [{
						required: true,
						message: '请选择客户来源',
						trigger: 'change'
					}, ],
					opportunitySource: [{
						required: true,
						message: '请选择来源渠道',
						trigger: 'change'
					}, ],
					creditCode: [{
						required: true,
						message: '请输入统一社会信用代码',
						trigger: 'blur'
					}, ],
					customerStatus: [{
						required: true,
						message: '请客户状态',
						trigger: 'change'
					}, ],
					customerLabels: [{
						required: true,
						message: '请选择客户标签',
						trigger: 'change'
					}, ],
					followupTime: [{
						required: true,
						message: '请选择跟进时间',
						trigger: 'change'
					}, ],
					staffId: [{
						required: true,
						message: '请输入跟进人员',
						trigger: 'blur'
					}, ],
				},
				list: [{}],
				loading: false,
				teamOptions: '', //业务经理
				cropNameArr: [], //作物名称
				productList: [], //产品名称
			}
		},
		created() {
			this.opportunityId = this.$route.query.opportunityId ? this.$route.query.opportunityId : ''
			this.customerId = this.$route.query.customerId ? this.$route.query.customerId : ''
			if (this.customerId != '') {
				const obj = Object.assign({}, this.$route, {
					title: "编辑客户"
				});
				this.$tab.updatePage(obj);
				this.getCustomerDetail()
			} else if (this.opportunityId != '') {
				//商机客户
				this.getOpportunityInfo1()
			}
			this.getUserList()
			this.getProduct()

		},
		methods: {
			// 转为客户页面进来
			getOpportunityInfo1() {
				getOpportunityInfo(this.opportunityId).then(response => {
					this.form = response.data;
					this.form.followupRecords = {
						followupTime: '', //跟进时间
						followupContent: '', //跟进内容
						staffId: '', //跟进人员
						reminderMethod: '', //提醒方式
						reminderType: '', //任务提醒
					} //跟进任务
					this.addressNode = [this.form.localProvince, this.form.localCity, this
						.form.localCounty
					]
					// , this.form.localArea
					this.form.cropStructuresList = [{
						cropType: '', //类型1=作物结构2=销售情况
						cropYear: '', //年份
						cropVariety: '', //作物品种农户来源作物表的id
						cropArea: '', //种植面积（亩）
						cropCost: '', //农资年投入成本(元)
						cropMonth: '', //种植月份
						mainProducts: '', //主营产品经销商或零售有。来源作物id
						salesVolume: '' //销售规模(万元)
					}] //作物结构或销售情况
				});
			},
			getProduct() {
				productListAll().then(res => {
					this.productList = res.data
				})
			},
			closePage() {
				this.$tab.closePage();
			},
			// 重置
			resetQuery() {
				this.resetForm("queryRef");
				// console.log(this.form,'quer===')
			},
			// 客户详情
			getCustomerDetail() {
				getCustomerDetail(this.customerId).then(res => {
					this.form = res.data
					//不存在跟进信息
					if(!this.form.followupRecords){
						this.form.followupRecords = {
							followupTime: '', //跟进时间
							followupContent: '', //跟进内容
							staffId: '', //跟进人员
							reminderMethod: '', //提醒方式
							reminderType: '', //任务提醒
						}
					}else{
						this.form.followupTime = this.form.followupRecords.followupTime
						this.form.staffId = this.form.followupRecords.staffId
						this.form.followupContent = this.form.followupRecords.followupContent
					}
					
					this.addressNode = [this.form.localProvince, this.form.localCity, this
						.form.localCounty
					]
					// , this.form.localArea
				})
			},
			handleAvatarSuccess(e) {
				console.log(e, 'e1')
				this.form.storeImageUrl = e.url
			},
			beforeAvatarUpload(e) {
				console.log(e, 'e2')
			},
			// 选择地址
			handleChangeAddress(e) {
				// console.log(e, this.form.localProvince)
				this.form.localProvince = e[0] //省
				this.form.localCity = e[1] //市
				this.form.localCounty = e[2] //县
				// this.form.localArea = e[3] //区
				let nodesObj = this.$refs["cascader"].getCheckedNodes()[0].pathLabels;
				this.form.localProvinceName = nodesObj[0] //省
				this.form.localCityName = nodesObj[1] //市
				this.form.localCountyName = nodesObj[2] //县
				// this.form.localAreaName = nodesObj[3] //区
			},
			change1(e) {
				this.form.birthday = this.filterTime(e)
			},
			change2(e) {
				this.form.followupTime = this.filterTime(e)
				this.form.followupRecords.followupTime = this.filterTime(e)
			},
			filterTime(dateString) {
				// 使用 Date.parse 解析字符串为时间戳（毫秒），然后创建 Date 对象
				const date = new Date(Date.parse(dateString));

				// 提取各个部分
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1，并补零
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');

				// 拼接成所需的格式
				const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

				return formattedDate
			},
			// 创建客户
			creatUser(formName) {
				if(this.opportunityId != ''){
					this.form.opportunityId = this.opportunityId
					this.form.id = ''
				}
				this.$refs[formName].validate((valid) => {
					if (valid) {
						// 新增
						this.form.followupRecords.staffId = this.form.staffId
						this.form.followupRecords.followupContent = this.form.followupContent
						for (let i in this.form.cropStructuresList) {
							this.form.cropStructuresList[i].cropType = this.form.customerType ==
								'1003' ? 1 : 2
						}
						if (this.customerId == '') {
							customerAdd(this.form).then(response => {
								this.$message({
									message: '添加成功',
									type: 'success'
								});
								setTimeout(() => {
									this.closePage()
								}, 1500)
							})
						} else {
							// 编辑
							this.form.followupRecords = null
							for (let key in this.form.cropStructuresList) {
								delete this.form.cropStructuresList[key].id
							}
							editCustomer(this.form).then(response => {
								this.$message({
									message: '编辑成功',
									type: 'success'
								});
								setTimeout(() => {
									this.closePage()
								}, 1500)
							})
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			// 获取作物列表
			cropVariety() {
				cropVariety().then(response => {
					console.log(response, 'response')
					this.cropNameArr = response.rows
				})
			},
			// 删除
			del(index, rows) {
				rows.splice(index, 1);
			},
			/**
			 * 获取本人和下级用户数据
			 */
			getUserList() {
				//获取自己和同部门的用户信息
				getUserListData().then(response => {
					this.teamOptions = response.data;
				});
				this.cropVariety()
			},
			handleAdd() {
				let item = {
					cropType: '', //类型1=作物结构2=销售情况
					cropYear: '', //年份
					cropVariety: '', //作物品种农户来源作物表的id
					cropArea: '', //种植面积（亩）
					cropCost: '', //农资年投入成本(元)
					cropMonth: '', //种植月份
					mainProducts: '', //主营产品经销商或零售有。来源作物id
					salesVolume: '' //销售规模(万元)
				}
				this.form.cropStructuresList.push(item)
			}
		}
	}
</script>

<style>
	.avatar-uploader .el-upload {
		background: #F7F8FA;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
		width: 110px;
		height: 110px;
		text-align: center;
		line-height: 22px;
		color: #8c939d;
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		text-align: center;
	}

	.shopImg {
		width: 110px;
		height: 110px;
	}
</style>